#! /usr/bin/env python
# -*- coding: utf-8 -*-

# *************************************************************
#  Copyright (c) Huoty - All rights reserved
#
#      Author: Huoty <sudohuoty@gmail.com>
#  CreateTime: 2016-10-07 21:40:45
# *************************************************************

"""图灵机器人接口"""

import os
import time
import json
import random
import contextlib

import requests


TURING_API    = "http://www.tuling123.com/openapi/api"
QIZHI_API     = "http://api.smartnlp.cn/cloud/robot/57f8b4b310000048a9564642/answer"
MOLI_API      = "http://i.itpk.cn/api.php"
QINGYUNKE_API = "http://api.qingyunke.com/api.php"


def request_answer(url, payload=None):
    headers = {'Content-type': 'text/html', 'charset': 'utf-8'}
    req = requests.get(url, headers=headers, params=payload, timeout=6)
    req.raise_for_status()
    return req.content.decode('utf-8')

def turing(info, userid=None, loc=None):
    """图灵机器人"""
    params = {"key": os.environ["TURING_ZHIDOU_APIKEY"], "info": info}
    if userid:
        params["userid"] = userid
    if loc:
        params["loc"] = loc

    req = request_answer(TURING_API, payload=params)
    req = json.loads(req)
    req.pop("code")
    return req

def qizhi(answer):
    """奇智机器人"""
    req = request_answer(QIZHI_API, payload={'q': answer})
    req = json.loads(req)
    answers = req["answers"][0]
    return {"text": answers["respond"], "score": answers["score"]}

def qingyunke(msg):
    """青云客智能聊天机器人"""
    params = {"key": "free", "appid": 0, "msg": msg}
    req = request_answer(QINGYUNKE_API, payload=params)
    req = json.loads(req)
    if req["result"] != 0:
        raise Exception("qingyunke return error code: %s" % req)
    return {"text": req["content"]}

def moli(question):
    """茉莉机器人"""
    params = {
        "api_key": os.environ["MOLI_APIKEY"],
        "api_secret": os.environ["MOLI_SECRET"],
        "limit": random.randint(4, 8),
        "type": "json",
        "question": question,
    }
    req = request_answer(MOLI_API, payload=params)
    try:
        return json.loads(req)
    except ValueError:
        return {"text": req}

__all__ = [
    "turing",
    "qizhi",
    "qingyunke",
    "moli",
]


# Script starts from here

if __name__ == "__main__":
    pass
